<script lang="ts" setup>
import type { TableColumnCtx } from "element-plus"

import type { VNode } from "vue"
import { batchRemoveCreditorData, removeCreditorData } from "@@/apis/users/creditor"

import { h, onMounted, ref } from "vue"

import { useForm } from "./useForm"
import { useTable } from "./useTable"

const {
  tableData,
  searchParams,
  currentPage,
  pageSize,
  total,
  fetchData,
  handlePageChange,
  handleSizeChange
} = useTable()

const {
  formData,
  formRules,
  formDataRef,
  addDialogVisible,
  isEdit,
  showDialog,
  submitForm,
  closeDialog
} = useForm(fetchData)

const selectable = (row: any) => ![1, 2].includes(row.id)

function handleEdit(row: any) {
  formData.value = { ...row }
  isEdit.value = true
  showDialog()
}
const multipleSelection = ref([])
function handleSelectionChange(val: []) {
  multipleSelection.value = val
}

function handleRemove(row: any) {
  ElMessageBox.confirm(
    "确认删除吗?",
    "提示！",
    {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning"
    }
  )
    .then(async () => {
      await removeCreditorData(row.id)
      fetchData()
      ElMessage.success("删除成功！")
    })
}

function batchDelete() {
  console.log(multipleSelection)
  if (multipleSelection.value.length === 0) return ElMessage.warning("请选择要删除的项")

  ElMessageBox.confirm(
    "确认删除吗?",
    "提示！",
    {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning"
    }
  )
    .then(async () => {
      const ids = multipleSelection.value.map((item: any) => item.id)
      await batchRemoveCreditorData({ ids })
      fetchData()
      ElMessage.success("删除成功！")
    })
}

function getSummaries(param: { columns: TableColumnCtx<any>[], data: any[] }) {
  const { columns, data } = param
  const sums: (string | VNode)[] = []

  columns.forEach((column, index) => {
    if (index === 1) {
      sums[index] = h("div", {}, ["Total"])
      return
    }

    if (column.property === "executeMoney") {
      const sum = data.reduce((prev: number, curr: any) => {
        const value = curr?.executeMoney !== undefined ? Number(curr.executeMoney) : 0
        return !Number.isNaN(value) ? prev + value : prev
      }, 0)

      sums[index] = h("span", { style: "color: var(--el-color-primary)" }, [`${sum.toFixed(2)} 万`])
    }
  })

  return sums
}

// 初始化加载数据
onMounted(() => {
  fetchData()
})
</script>

<template>
  <div class="view-container">
    <!-- 操作栏 -->
    <div class="view-header">
      <div>
        <el-input v-model="searchParams.caseNo" placeholder="输入名称搜索" style="width: 300px; margin-right: 10px;" />
        <el-button type="primary" @click="fetchData">
          搜索
        </el-button>
      </div>
      <div>
        <el-button type="primary" @click="showDialog">
          添加债权人
        </el-button>
        <el-button type="danger" @click="batchDelete">
          批量删除
        </el-button>
      </div>
    </div>

    <!-- 列表 -->
    <div class="view-main">
      <el-table
        :data="tableData" @selection-change="handleSelectionChange" border style="height:100%;width: 100%"
        :summary-method="getSummaries" show-summary
      >
        <el-table-column type="selection" :selectable="selectable" width="55" />

        <el-table-column prop="caseNo" label="案号" width="100" sortable>
          <template #default="{ row }">
            <div class="top-badge">
              <span>{{ row.caseNo }}</span>
              <div>
                <span v-if="row.remark" class="top-badge-bg" />
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="caseNo" label="案号 / 法院" width="340">
          <template #default="{ row }">
            <div>
              (2025)闽0121执 <el-text type="primary">
                {{ row.caseNo }}
              </el-text> 号
              <span>/ 闽侯县人民法院</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="creditorName" label="债权人名称" width="180" />
        <el-table-column prop="executeMoney" label="执行金额" width="180" sortable>
          <template #default="{ row }">
            <el-text type="primary">
              {{ row.executeMoney.toFixed(2) }} 万
            </el-text>
          </template>
        </el-table-column>
        <el-table-column prop="executeTime" label="执行时间" width="200" />
        <el-table-column prop="remark" label="备注" />
        <el-table-column fixed="right" label="操作" width="140">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button link type="danger" size="small" @click="handleRemove(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="view-footer">
      <el-pagination
        background layout="total,sizes, prev, pager, next" :total="total"
        v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[20, 50, 100, 200]"
        @current-change="handlePageChange" @size-change="handleSizeChange"
      />
    </div>

    <!-- 添加对话框 -->
    <el-dialog v-model="addDialogVisible" :title="isEdit ? '编辑' : '添加'" :close-on-click-modal="false" @close="closeDialog" align-center>
      <el-form :model="formData" label-width="100px" :rules="formRules" ref="formDataRef">
        <el-form-item label="案号" prop="caseNo">
          <el-input v-model="formData.caseNo" />
        </el-form-item>
        <el-form-item label="债权人名称" prop="creditorName">
          <el-input v-model="formData.creditorName" />
        </el-form-item>
        <el-form-item label="执行金额" prop="executeMoney">
          <el-input-number v-model="formData.executeMoney" controls-position="right" />
        </el-form-item>
        <el-form-item label="执行时间" prop="executeTime">
          <el-date-picker v-model="formData.executeTime" type="date" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" :rows="4" type="textarea" />
        </el-form-item>
        <el-form-item label-width="0">
          <div style="width: 100%;display: flex;justify-content: center;gap: 20px;">
            <el-button style="width: 120px;" @click="closeDialog">
              取 消
            </el-button>
            <el-button style="width: 120px;" type="primary" @click="submitForm(formDataRef)">
              提 交
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.top-badge {
  .top-badge-bg {
    position: absolute;
    left: 0;
    top: 0;
    width: 0;
    height: 0;
    border-style: solid;
    border-width: 0 16px 16px 0;
    /* 右上方向的三角形 */
    border-color: transparent red transparent transparent;
    /* 红色三角形 */
    transform: rotate(-90deg);
    /* 斜着的效果 */
    margin: 2px 0 0 2px;
    /* 微调位置 */
  }
}
</style>
